<template>
  <div class="containter">
    <!--面包屑导航区域-->
    <div class="header">--- 上传培训记录 ---</div>
    <el-card subject="添加培训记录" :visible="true">
      <!-- <span>这是一段信息</span> -->
      <el-form
        :model="addRecordForm"
        ref="addRecordForm"
        label-width="90px"
        :rules="addRecordRules"
      >
        <el-form-item label="培训组" prop="groupId">
          <el-cascader
            v-model="addRecordForm.groupId"
            placeholder="培训组"
            :options="groupTypeOptions"
            ref="refSelect"
            @change="handleChange"
            :props="{
              checkStrictly: true,
              value: 'groupId',
              label: 'groupName',
              emitPath: false,
            }"
            size="medium"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="培训主题" prop="subject">
          <el-input v-model="addRecordForm.subject"></el-input>
        </el-form-item>
        <el-form-item label="主讲人" prop="lecturer">
          <el-input v-model="addRecordForm.lecturer"></el-input>
        </el-form-item>
        <el-form-item label="教师参与" prop="isWithTea">
          <el-select v-model="addRecordForm.isWithTea" placeholder="请选择">
            <el-option
              v-for="item in isWithTeaType"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addRecordForm.isWithTea == 1"
          label="培训老师"
          prop="teacher"
        >
          <!-- <el-input
              v-model="addRecordForm.teacher"
              placeholder="老师名字之间请用中文逗号连接"
            ></el-input> -->
          <el-select
            v-model="addRecordForm.teacher"
            filterable
            multiple
            placeholder="请选择指导老师（可搜索姓名）"
          >
            <el-option
              v-for="item in teaList"
              :key="item.teacherId"
              :value="item.teacherId"
              :label="item.teacherName"
            >
              <span style="float: left">{{ item.teacherName }}</span>
              <span style="float: right; color: #8492a6; font-size: 80%">{{
                item.teacherId
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训地点" prop="location">
          <el-input
            v-model="addRecordForm.location"
            placeholder="格式：西407；A118"
          ></el-input>
        </el-form-item>
        <el-form-item label="培训日期" prop="date">
          <el-date-picker
            v-model="trainingDate.date"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="培训时间" prop="time">
          <el-time-select
            v-model="trainingDate.time"
            value-format="HH:mm:ss"
            :picker-options="{
              start: '06:30',
              step: '00:30',
              end: '23:00',
            }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="培训时长" prop="duration">
          <el-input
            v-model="addRecordForm.duration"
            type="number"
            placeholder="单位：分钟"
          >
            <template slot="append">分钟</template></el-input
          >
        </el-form-item>
        <el-form-item label="培训对象" prop="students">
          <el-input v-model="addRecordForm.students">
            <el-select
              v-model="addRecordForm.grade"
              style="width: 120px"
              slot="prepend"
              placeholder="请选择级别"
            >
              <el-option
                v-for="(item, key) in gradeOptions"
                :key="key"
                :label="item + '级'"
                :value="item"
              ></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="培训内容" prop="detail">
          <el-input
            v-model="addRecordForm.detail"
            autosize
            type="textarea"
            rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="addRecordForm.remark"
            autosize
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="培训照片" prop="imgs">
          <el-upload
            ref="upload_attach"
            :action="uploadUrl"
            :headers="token"
            list-type="picture-card"
            accept="image/*"
            :limit="imgLimit"
            :file-list="fileList"
            :auto-upload="false"
            multiple
            :on-preview="handlePictureCardPreview"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"
            :on-error="imgUploadError"
            :on-change="handleFileChange"
            :on-remove="handleFileChange"
            width="100%"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png等图片，且每张图片不超过2Mb
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <div id="sumitButtons">
        <el-button @click="cancelRecord()">重 置</el-button>
        <el-button type="primary" @click="submitRecord('addRecordForm')"
          >确 定</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import configList from "../config.js";
import loading from "../../loading.js";
export default {
  data() {
    //判断函数
    var validateteacher = (rule, value, callback) => {
      if (this.addRecordForm.isWithTea == false) {
        callback();
      } else if (value == "") {
        callback(new Error("选择有指导老师参与时，请填写指导老师姓名"));
      } else {
        callback();
      }
    };
    var validateDate = (rule, value, callback) => {
      // console.log("date", this.trainingDate.date);
      if (this.trainingDate.date === "") {
        callback(new Error("培训日期不能为空"));
      } else {
        callback();
      }
    };
    var valitrainingDate = (rule, value, callback) => {
      if (this.trainingDate.time === "") {
        callback(new Error("培训时间不能为空"));
      } else {
        callback();
      }
    };
    var validateImg = (rule, value, callback) => {
      if (this.fileLength < 1) {
        callback(new Error("请至少上传一张培训图片"));
      } else {
        callback();
      }
    };
    var validateDuration = (rule, value, callback) => {
      if (this.addRecordForm.duration < 1) {
        callback(new Error("请输入大于0的培训时长"));
      } else {
        callback();
      }
    };
    return {
      upload: {
        text: "点击上传培训记录",
        status: false,
      },
      totalRecord: 0,
      recordList: [],
      offset: 9,
      addRecordForm: {
        isWithTea: 0,
        duration: 0,
        groupId: [],
        students: "全组学员",
        grade: "",
        files: [],
        teacher: "",
        remark: "",
      },
      groupTypeOptions: [],
      gradeOptions: [],
      teaList: [],
      trainingDate: {
        date: "",
        time: "",
      },
      fileList: [],
      fileLength: 0,
      dialogVisible: false,
      dialogImageUrl: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      token: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      data: {
        isWithTea(is) {
          if (typeof is == "undefined") return "否";
          else if (is == 1) return "否";
          else return "是";
        },
      },
      addRecordRules: {
        groupId: [{ required: true, message: "请选择培训组", trigger: "blur" }],
        subject: [
          { required: true, message: "培训主题不能为空", trigger: "blur" },
        ],
        lecturer: [
          { required: true, message: "主讲人不能为空", trigger: "blur" },
        ],
        teacher: [{ validator: validateteacher, trigger: "blur" }],
        location: [
          { required: true, message: "培训地点不能为空", trigger: "blur" },
        ],
        date: [{ validator: validateDate, trigger: "blur" }],
        time: [{ validator: valitrainingDate, trigger: "blur" }],
        duration: [{ validator: validateDuration, trigger: "blur" }],
        students: [
          { required: true, message: "培训对象不能为空", trigger: "blur" },
        ],
        detail: [
          { required: true, message: "培训内容不能为空", trigger: "blur" },
        ],
        imgs: [{ validator: validateImg, trigger: "blur" }],
      },
    };
  },
  // beforeCreate() {

  // },

  created() {
    this.imgLimit = configList.imgLimit;
    this.uploadUrl = configList.uploadUrl;
    this.isWithTeaType = configList.isWithTeaType;
    this.addRecordForm.groupId = window.JSON.parse(
      window.sessionStorage.getItem("groupId")
    );
    // this.addRecordForm.groupId = 11010;
    // this.teaList = teaList.list;
    // this.getTeacherList();
  },

  mounted() {
    this.initConfig();
    console.log("gid", this.addRecordForm.groupId);
  },

  methods: {
    initConfig() {
      // Grade
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      // console.log("m", month);
      let grade = [];
      if (month >= 8) grade.push(year--);
      while (year >= 2019) {
        grade.push(year);
        year--;
      }
      this.gradeOptions = grade;
      this.addRecordForm.grade = this.gradeOptions[0];
      // Group Type
      this.getGroupType();
      // TechaerList
      this.getTeacherList();
    },
    async getTeacherList() {
      if (window.sessionStorage.getItem("teaList") != null) {
        this.teaList = JSON.parse(window.sessionStorage.getItem("teaList"));
        console.log("已从本地取得TeaList！");
        return;
      }
      const res = await this.$axios.get(`${this.HOST}/teacher/api/teacher`);
      // console.log("teaRes", res);
      if (res.data.meta.code == 200) {
        this.teaList = res.data.data.teachers;
        window.sessionStorage.setItem("teaList", JSON.stringify(this.teaList));
        console.log("获取教师列表成功！", this.teaList);
      }
    },
    async getGroupType() {
      let gid = JSON.parse(window.sessionStorage.getItem("groupId"));
      if (gid == null) {
        this.queryInfo.groupId = [10000];
      }
      if (window.sessionStorage.getItem("groupTree") != null) {
        this.groupTypeOptions = JSON.parse(
          window.sessionStorage.getItem("groupTree")
        );
        console.log("已从本地获得GroupTree！", this.groupTypeOptions);
        return;
      }
      const res = await this.$axios.get(`${this.HOST}/group/api/groupTree`);
      if (res.data.meta.code == 200) {
        let arr = [];
        arr.push(res.data.data.groupTree);
        this.groupTypeOptions = arr;
        console.log("组别获取成功！", this.groupTypeOptions);
        window.sessionStorage.setItem(
          "groupTree",
          JSON.stringify(this.groupTypeOptions)
        );
        // console.log(this.queryInfo.groupId);
      } else if (res.status != 200) {
        this.$message({
          message: "获取失败！",
          type: "error",
        });
      }
    },
    handleChange: function () {
      // console.log(this.addRecordForm);
    },

    async submitRecord(formName) {
      let isValid = true;
      this.$refs[formName].validate(async (valid) => {
        if (!valid) {
          isValid = false;
          return;
        }
      });
      if (!isValid) return;
      // if (this.fileLength == 0) {
      //   this.$message({
      //     message: "请至少选择一张图片上传！",
      //     type: "warning",
      //   });
      // }
      // console.log("fL",this.$refs.upload_attach);

      // this.$refs.upload_attach.submit();
      // console.log("fileList", this.fileList);
      var teacher = null;
      if (typeof this.addRecordForm.teacher != "undefined") {
        teacher = this.addRecordForm.teacher.toString();
      }
      console.log("groupId", this.addRecordForm.groupId);
      const params = {
        groupId: isNaN(this.addRecordForm.groupId)
          ? parseInt(
              this.addRecordForm.groupId[this.addRecordForm.groupId.length - 1]
            )
          : this.addRecordForm.groupId,
        lecturer: this.addRecordForm.lecturer,
        subject: this.addRecordForm.subject,
        detail: this.addRecordForm.detail,
        trainingDate:
          this.trainingDate.date + " " + this.trainingDate.time + ":00",
        duration: this.addRecordForm.duration,
        trainingLocation: this.addRecordForm.location,
        isWithTea: this.addRecordForm.isWithTea,
        teacher: teacher,
        students: this.addRecordForm.students,
        grade: this.addRecordForm.grade,
        remark: this.addRecordForm.remark,
        // files: param.file,
      };
      let formData = new FormData();
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key]);
      });
      this.fileList.forEach((file) => {
        formData.append("files", file.raw);
      });
      console.log("formdata", formData);
      // 开始上传
      const _loading = loading(`上传中，请稍等...`);
      const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
          );
          _loading.setText(
            "培训记录上传中，进度：" + this.progressPercent + "%"
          ); //更新dialog进度，优化体验
          // console.log(this.progressPercent);
        },
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      try {
        const res = await this.$axios.post(
          `${this.HOST}/record/api/uploadTrainingRecord`,
          formData,
          config
        );
        // console.log("res=", res);
        if (res.data.meta.code != 200) {
          this.$message({
            message: res.data.data.msg,
            type: "error",
          });
          return;
        }
        // =========== 执行 ============
        this.$message({
          message: "上传成功！",
          type: "success",
        });

        this.$router.replace("/reviewRecords");
        this.addRecordForm = {};
        this.dialogImageUrl = "";
      } finally {
        _loading.close();
      }
    },
    cancelRecord: function () {
      let temp = this.addRecordForm;
      this.addRecordForm = {
        groupId: temp.groupId,
        grade: temp.grade,
        students: temp.students,
        isWithTea: 0,
      };
    },
    handlePictureCardPreview(file) {
      //预览图片时调用
      // console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleFileChange(file, fileList) {
      // console.log("file", file);
      // console.log("fileList", fileList);
      console.log("file", file);
      // const isJPG = true;
      const isLt2M = file.size / 1024 / 1024 < 2;

      this.fileList = fileList;
      this.fileLength = fileList.length;

      if (!isLt2M) {
        this.$message.warning("上传图片大小不能超过 2MB!");
        this.fileList.pop();
        this.fileLength--;
      }
    },
    handleSuccess(res, file) {
      //图片上传成功
      // this.fileList.push(file)
      // console.log(res);
      // console.log("file",file);
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleExceed(files, fileList) {
      //图片上传超过数量限制
      this.$message.error("上传图片不能超过6张!");
      // console.log(files, fileList);
    },
    imgUploadError(err, file, fileList) {
      //图片上传失败调用
      // console.log(err);
      // console.log(file, fileList);
      // this.$message.error("上传图片失败!");
    },
    showPic() {
      this.settingDialogVisible = !this.settingDialogVisible;
    },
  },
};
</script>

<style lang="less" scoped>

/depp/.el-input__inner {
  width: 400px !important;
}

.containter {
  width: 75%;
  min-width: 1000px;
  margin: auto;

  .header {
    color: white;
    font-size: 28px;
    font-weight: bold;
    width: 100%;
    text-align: center;
    height: 50px;
  }
}

#sumitButtons {
  width: 300px;
  margin: 0px auto;
}
</style>
